package android.gpsmessenger;

import java.util.*;

import android.content.Context;
import android.graphics.Color;

import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;

import android.widget.TextView;
import android.widget.ArrayAdapter;


public class ContactAdapter extends ArrayAdapter<Contact>
{
	 private List<Contact> _contacts;
	 private Context _context;
	 private int _selectedPosition ;
	 private int _resLayout;
	 
	 public ContactAdapter(Context context, int textViewResourceId, List<Contact> contacts) 
	 {
		 super(context, textViewResourceId, contacts);
		 _contacts = contacts;
		 _context  = context;
		 _resLayout = textViewResourceId;
		 _selectedPosition = -1;
	 }
	 
	 public int getCount() 
	 {
		 return _contacts.size();
	 }

	 public Contact getItem(int position) 
	 {
		 return _contacts.get(position);
	 }

	 public long getItemId(int position) 
	 {
		 return position;
	 }

	 public int getSelectedPosition()
	 {
		 return _selectedPosition;
	 }
	 
	 public void setSelectedPosition(int position)
	 {
		 _selectedPosition = position;
		 // inform the view of this change
		 notifyDataSetChanged();
	 }
	 
	 public void setContacts(List<Contact> contacts)
	 {
		 _contacts = contacts;
	 }
	 
	 public View getView(int position, View convertView, ViewGroup parent) 
	 {
		 Holder holder;
		 
		 if (convertView == null) 
		 {
			 LayoutInflater li = (LayoutInflater) getContext().getSystemService(
	                    Context.LAYOUT_INFLATER_SERVICE);
	         convertView = li.inflate(_resLayout, parent, false);
	            
			 holder = new Holder();
			 holder.txtName = (TextView) convertView.findViewById(R.id.name);
			 holder.txtPhone = (TextView) convertView.findViewById(R.id.phone);
			 holder.txtEmail = (TextView) convertView.findViewById(R.id.email);
	   
			 convertView.setTag(holder);
		 } 
		 else
			 holder = (Holder) convertView.getTag();
	 
	  
		 Contact contact = (Contact) _contacts.get(position);
		 if (contact != null)
		 {
			 holder.txtName.setText(contact.getName());
			 holder.txtPhone.setText(contact.getPhone());
			 holder.txtEmail.setText(contact.getEmail());
		 }
		 
		 if (getSelectedPosition() == position)
			 convertView.setBackgroundColor(Color.CYAN);
		 else
			 convertView.setBackgroundColor(Color.WHITE);
		 
		 return convertView;
	 }
	 
	 static class Holder 
	 {
		 TextView txtName;
		 TextView txtPhone;
		 TextView txtEmail;
	 }
}